'''
Description: 
    根据描述文件生成与修改配置文件并另存
    new dependecy openpyxl
Author: 
LastEditors: M
'''
import os,copy
import json
import shutil
import pandas as pd
import compoments.config as CFG 
import compoments.utils as U
from  compoments.utils import errormsg
from compoments.settings import load_setting

class ConfigBuilder():
    """
    生成配置
    """
    setting:pd.DataFrame = None
    setting_file_fp = os.path.join(CFG.PIKER_DIR,CFG.setting_file)
    def __init__(self) -> None:

        self.setting = self._get_setting_sheet()
        #Todo check json 正确性

    def _get_base_cfg(self,rp):
        """
        获取实验基础配置 base_cfg_file
        """ 
        return U.load_json(os.path.join(CFG.PROJECT_DIR,rp))
    def _get_setting_sheet(self):
        """
        获取piker 生成的配置表格内容 
        """
        fp = self.setting_file_fp
        return load_setting(fp)

    def _save_setting(self):
        if self.setting is not None:
            self.setting.to_excel(U.get_setting_fp())
        pass

    def _set_next_dict(self,frm,to):
        """
        将字典frm 设置到to中去
        return to
        """
        for k in frm:
            if k in to:
                if type(frm[k]) is dict:
                    self._set_next_dict(frm[k],to[k])
                else:
                    to[k] = frm[k]
            else:
                to[k] = frm[k]
        return to
        
    def _set_new_cfg(self,base:dict,amend:dict):
        """
        kws:{
            "sectionA":{
                "option_a":12
            }
        }
        """
        ncfg = copy.deepcopy(base)
        self._set_next_dict(amend,ncfg)
        return ncfg

    def _gen_exp_cfg_file(self,fp,cfg):
        """
        生成一个新的config
        将cfg 存储到 fp
        """
        if not os.path.isabs(fp):
            fp = U.get_root_path(fp)
        if not os.path.exists(os.path.dirname(fp)):
            os.makedirs(os.path.dirname(fp))
        json.dump(cfg,open(f"{fp}","w",encoding='utf-8'),indent=4)
        return True
    
    def run(self):
        st = self.setting
        for i in range(len(st)):
            try:            
                exp = st.iloc[i]
                if exp['state']!=0:
                    print(U._ok_("skip"),exp['id'])
                    continue
                base_cfg = self._get_base_cfg(exp['base_cfg_file'])
                amend_cfg = json.loads(exp['amend_cfg']) 
                new_cfg = self._set_new_cfg(base_cfg,amend_cfg)
                self._gen_exp_cfg_file(os.path.join(CFG.PROJECT_DIR,exp['save_dir'],exp['name']),new_cfg)
            
            except Exception as e:
                print(exp)
                errormsg("生成参数文件失败,检查文件内容是否正确",emphasis=f"{self.setting_file_fp}\n\t{str(e)}")
                exit(-1)
        print(U._ok_(f"生成参数配置文件成功,共{len(st)}份"))
